package com.yonyou.brigade.rtpnr.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.order_center.model.*;
import com.yonyou.brigade.order_center.service.*;
import com.yonyou.brigade.rtpnr.model.*;
import com.yonyou.brigade.rtpnr.service.IRtpnrOrderService;
import com.yonyou.brigade.rtpnr.service.IRtpnrPublicService;
import com.yonyou.brigade.rtpnr.service.IRtpnrUserService;
import com.yonyou.brigade.rtpnr.util.OrderConvert;
import com.yonyou.brigade.util.HttpClientUtil;
import com.yonyou.brigade.ybz.service.IConvertService;
import com.yonyou.ybzboot.starter.mongodb.dao.IMongoDao;
import com.yonyou.ybzboot.starter.mongodb.model.CriteriaMap;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2018/6/14.
 */
@Service
public class RtpnrOrderServiceImpl implements IRtpnrOrderService {

    @Autowired
    @Qualifier("rtpnrPublicServiceImpl")
    private IRtpnrPublicService rtpnrPublicService;

    @Autowired
    @Qualifier("briFlightOrderServiceImpl")
    private IBriFlightOrderService briFlightOrderService;

    @Autowired
    @Qualifier("briTrainOrderServiceImpl")
    private IBriTrainOrderService briTrainOrderService;

    @Autowired
    @Qualifier("briHotelOrderServiceImpl")
    private IBriHotelOrderService briHotelOrderService;

    @Autowired
    @Qualifier("briHotelRoomServiceImpl")
    private IBriHotelRoomService hotelRoomService;

    @Autowired
    @Qualifier("briHotelApprovalFlowServiceImpl")
    private IBriHotelApprovalFlowService hotelApprovalFlowService;

    @Autowired
    @Qualifier("briFlightInfoServiceImpl")
    private IBriFlightInfoService flightInfoService;

    @Autowired
    @Qualifier("briFlightOrderContactServiceImpl")
    private IBriFlightOrderContactService orderContactService;

    @Autowired
    @Qualifier("briFlightPassengerServiceImpl")
    private IBriFlightPassengerService passengerService;

    @Autowired
    @Qualifier("briTrainPassengerServiceImpl")
    private IBriTrainPassengerService briTrainPassengerService;

    @Autowired
    @Qualifier("briTrainTicketServiceImpl")
    private IBriTrainTicketService briTrainTicketService;

//    @Autowired
//    @Qualifier("briTrainPaymentServiceImpl")
//    private IBriTrainPaymentService briTrainPaymentService;

    @Autowired
    @Qualifier("briTrainApprovalFlowServiceImpl")
    private IBriTrainApprovalFlowService briTrainApprovalFlowService;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService userCenterService;

    @Autowired
    @Qualifier("rtpnrUserServiceImpl")
    private IRtpnrUserService rtpnrUserService;

    @Autowired
    @Qualifier("convertServiceImpl")
    private IConvertService convertService;

    @Autowired
    @Qualifier("briOrderServiceImpl")
    private IBriOrderService briOrderService;

    @Autowired
    private IMongoDao mongoDao;

    @Value("${cnv.baigade.system.code}")
    private String systemCode;

    @Value("${cnv.register.userId}")
    private String cnvRegisterUserId;

    @Value("${cnv.register.tenant}")
    private String cnvRegisterTenant;

    @Value("${cnv.register.cookie}")
    private String cnvRegisterCookie;

    @Value("${rtpnr.tradeCarType}")
    private String rtpnrCarTradeType;

    @Value("${rtpnr.pub.tenant}")
    private String pubTenant;

    @Value("${ybz.matchApply4processes.url}")
    private String URL;

    @Value("${ybz.baseUrl}")
    private String ybzBaseUrl;

    private static final Logger logger = LoggerFactory.getLogger(RtpnrOrderServiceImpl.class);

    /**
     * 拉取机票订单
     *
     * @param tenant
     * @param orgpk
     */
    @Override
    public void getFlightOrderList(String tenant, String orgpk, int channelId, String begin, String end) {
        boolean has = true;
        GetFlightOrderList getFlightOrderList = new GetFlightOrderList();
        getFlightOrderList.setLastID("0");
        getFlightOrderList.setSearchDateType("1");
        getFlightOrderList.setStartDt(begin);
        getFlightOrderList.setEndDt(end);
        while (has) {
            JSONObject jsonObject = rtpnrPublicService.getFlightOrderList(tenant, orgpk, getFlightOrderList);
            if (jsonObject != null && jsonObject.containsKey("OrderList")) {
                JSONArray orderArray = jsonObject.getJSONArray("OrderList");
                if (orderArray != null && orderArray.size() > 0) {
                    for (int i = 0; i < orderArray.size(); i++) {
                        JSONObject orderJson = orderArray.getJSONObject(i);
                        getFlightOrderList.setLastID(orderJson.getString("LastID"));
                        saveFlight(orderJson, tenant, orgpk, channelId);
                    }
                } else {
                    has = false;
                }
            } else {
                has = false;
            }
        }
    }

    /**
     * 拉取火车票订单
     *
     * @param tenant
     * @param orgpk
     */
    @Override
    public void getTrainOrderList(String tenant, String orgpk, int channelId, String begin, String end) {
        boolean has = true;
        GetTrainOrderList getTrainOrderList = new GetTrainOrderList();
        getTrainOrderList.setLastID("0");
        getTrainOrderList.setStartDt(begin);
        getTrainOrderList.setEndDt(end);
        getTrainOrderList.setSearchDateType("1");
        while (has) {
            JSONObject jsonObject = rtpnrPublicService.getTrainOrderList(tenant, orgpk, getTrainOrderList);
            if (jsonObject != null && jsonObject.containsKey("OrderList")) {
                JSONArray orderArray = jsonObject.getJSONArray("OrderList");
                if (orderArray != null && orderArray.size() > 0) {
                    for (int i = 0; i < orderArray.size(); i++) {
                        JSONObject orderJson = orderArray.getJSONObject(i);
                        getTrainOrderList.setLastID(orderJson.getString("LastID"));
                        saveTrain(orderJson, tenant, orgpk, channelId);
                    }
                } else {
                    has = false;
                }
            } else {
                has = false;
            }
        }
    }

    /**
     * 拉取酒店订单
     *
     * @param tenant
     * @param orgpk
     */
    @Override
    public void getHotelOrderList(String tenant, String orgpk, int channelId, String begin, String end) {
        boolean has = true;
        GetHotelOrderList getHotelOrderList = new GetHotelOrderList();
        getHotelOrderList.setLastID("0");
        getHotelOrderList.setSearchDateType("1");
        getHotelOrderList.setStartDt(begin);
        getHotelOrderList.setEndDt(end);
        while (has) {
            JSONObject jsonObject = rtpnrPublicService.getHotelOrderList(tenant, orgpk, getHotelOrderList);
            if (jsonObject != null && jsonObject.containsKey("OrderList")) {
                JSONArray orderArray = jsonObject.getJSONArray("OrderList");
                if (orderArray != null && orderArray.size() > 0) {
                    for (int i = 0; i < orderArray.size(); i++) {
                        JSONObject orderJson = orderArray.getJSONObject(i);
                        getHotelOrderList.setLastID(orderJson.getString("LastID"));
                        saveHotel(orderJson, tenant, orgpk, channelId);
                    }
                } else {
                    has = false;
                }
            } else {
                has = false;
            }
        }
    }

    @Override
    public void getCarOrderList(String tenant, String orgpk, int channelId, String begin, String end) {
        GetCarOrderList getCarOrderList = new GetCarOrderList();
        getCarOrderList.setLastID("0");
        getCarOrderList.setStartDt(begin);
        getCarOrderList.setEndDt(end);
        getCarOrderList.setSearchDateType("1");
        // 是否公户
        boolean isPub = false;
        if (tenant.equals(pubTenant)) {
            isPub = true;
        }

        boolean has = true;
        while (has) {
            JSONObject jsonObject = rtpnrPublicService.getCarOrderList(tenant, orgpk, getCarOrderList);
            if (jsonObject != null && jsonObject.containsKey("OrderList")) {
                JSONArray orderArray = jsonObject.getJSONArray("OrderList");
                if (orderArray != null && orderArray.size() > 0) {
                    for (int i = 0; i < orderArray.size(); i++) {
                        JSONObject orderJson = orderArray.getJSONObject(i);
                        getCarOrderList.setLastID(orderJson.getString("LastID"));

                        GetCarOrderDetail getCarOrderDetail = new GetCarOrderDetail();
                        getCarOrderDetail.setOrderNo(orderJson.getString("OrderNO"));
                        JSONObject carOrderDetailJson = rtpnrPublicService.getCarOrderDetail(tenant, orgpk, getCarOrderDetail);
                        orderJson.put("OrderInfo", carOrderDetailJson.getJSONObject("OrderInfo"));
                        // mongodb save
                        CriteriaMap criteriaMap = new CriteriaMap();
                        criteriaMap.put("OrderInfo.OrderNo", orderJson.getString("OrderNO"));
                        List<JSONObject> ordersources = mongoDao.findByMap(criteriaMap, JSONObject.class, "rtpnr_car_orders");
                        if (ordersources != null && ordersources.size() > 0) {
                            mongoDao.deleteByMap(criteriaMap, "rtpnr_car_orders");
                            mongoDao.getMongoTemplate().save(orderJson, "rtpnr_car_orders");
                        } else {
                            mongoDao.getMongoTemplate().insert(orderJson, "rtpnr_car_orders");
                        }
                        //end mongodb save
                        JSONObject res = convertService.convert(rtpnrCarTradeType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, orderJson);

                        if (res.getBoolean("success")) {
                            JSONArray results = res.getJSONArray("result");
                            if (results != null && results.size() > 0) {
                                for (int j = 0; j < results.size(); j++) {
                                    JSONObject resultOne = results.getJSONObject(j);

                                    JSONObject orderCenter = JSON.parseObject(resultOne.getString("data"));
                                    if (orderCenter != null) {
                                        // 补全用户信息
                                        Wrapper<RtpnrUser> rtpnrUserWrapper = new EntityWrapper<>();
                                        rtpnrUserWrapper.eq("f_login_id", orderJson.getString("CreateBy"));
                                        RtpnrUser rtpnrUser = rtpnrUserService.selectOne(rtpnrUserWrapper);
                                        if (rtpnrUser != null) {
                                            orderCenter.put("userId", rtpnrUser.getMobile());
                                        }
                                        if (isPub) {
                                            // 公户逻辑，若果能查询到用户去用户的租户否则暂存在公户下
                                            String realTenant = rtpnrUser == null ? tenant : rtpnrUser.getTenant();
                                            briOrderService.saveCar(orderCenter, orderCenter.getString("orderNo"), realTenant, orderCenter.getString("userId"), ChannelEnum.RTPNR.getName(), channelId);
                                        } else {
                                            briOrderService.saveCar(orderCenter, orderCenter.getString("orderNo"), tenant, orderCenter.getString("userId"), ChannelEnum.RTPNR.getName(), channelId);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    has = false;
                } else {
                    has = false;
                }
            } else {
                has = false;
            }
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {})
    public void saveFlight(JSONObject orderJson, String tenant, String orgpk, int channelId) {
        boolean isPub = false;
        if (pubTenant.equals(tenant)) {
            isPub = true;
        }
        BriFlightOrder order = OrderConvert.getBriFlightOrderByJSON(orderJson);
        // 存储航班信息
        GetFlightOrderDetail detail = new GetFlightOrderDetail();
        detail.setOrderNo(order.getOrderNo());
        JSONObject detailJson = rtpnrPublicService.getFlightOrderDetail(tenant, orgpk, detail);
        detailJson.put("channelId", channelId);
        detailJson.put("curTime", new Date());
        // mongodb save
        CriteriaMap criteriaMap = new CriteriaMap();
        criteriaMap.put("OrderInfo.OrderNo", order.getOrderNo());
        List<JSONObject> ordersources = mongoDao.findByMap(criteriaMap, JSONObject.class, "rtpnr_flight_orders");
        if (ordersources != null && ordersources.size() > 0) {
            mongoDao.deleteByMap(criteriaMap, "rtpnr_flight_orders");
            mongoDao.getMongoTemplate().save(detailJson, "rtpnr_flight_orders");
        } else {
            mongoDao.getMongoTemplate().insert(detailJson, "rtpnr_flight_orders");
        }
        //end mongodb save
        // 拼装flightOrderDetail数据
        BriFlightOrder briFlightOrderDetail = null;
        briFlightOrderDetail = OrderConvert.getBriFlightOrderDetailByJSON(detailJson);
        briFlightOrderDetail.setOrderTime(order.getOrderTime());
        briFlightOrderDetail.setStatusType(order.getStatusType());
        briFlightOrderDetail.setYxDate(order.getYxDate());
        briFlightOrderDetail.setSavePrice(order.getSavePrice());
        briFlightOrderDetail.setTenant(tenant);
        briFlightOrderDetail.setSysUpdateTime(order.getSysUpdateTime());
        // 补全用户信息
        Wrapper<RtpnrUser> rtpnrUserWrapper = new EntityWrapper<>();
        rtpnrUserWrapper.eq("f_login_id", briFlightOrderDetail.getCreateBy());
        RtpnrUser rtpnrUser = rtpnrUserService.selectOne(rtpnrUserWrapper);
        if (null != rtpnrUser && StringUtils.isNotEmpty(rtpnrUser.getMobile())) {
            briFlightOrderDetail.setCreateBy(rtpnrUser.getUserName());
            try {
                // 公户处理逻辑
                UcUserDto ucUserDto;
                if (isPub) {
                    String realTenant = rtpnrUser.getTenant();
                    briFlightOrderDetail.setTenant(realTenant);
                    ucUserDto = userCenterService.getCompleteUcUserDtoByPhone(rtpnrUser.getMobile(), realTenant);
                } else {
                    ucUserDto = userCenterService.getCompleteUcUserDtoByPhone(rtpnrUser.getMobile(), tenant);
                }

                if (null != ucUserDto) {
                    if (!StringUtils.isEmpty(ucUserDto.getOrgPk())) {
                        if (!ucUserDto.getOrgPk().equals(orgpk)) {
                            //对于非该组织的人员不再插入数据
                            return;
                        }
                    }
                    briFlightOrderDetail.setUserId(ucUserDto.getUserId());
                    briFlightOrderDetail.setOrgPk(ucUserDto.getOrgPk());
                    briFlightOrderDetail.setDeptPk(ucUserDto.getDeptPk());
                    briFlightOrderDetail.setDepartment(ucUserDto.getDeptName());
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.toString());
            }
        }

        //根据申请单id补全申请单信息
        dealWithApplyFlight(tenant, briFlightOrderDetail);

        if (briFlightOrderDetail != null) {
            Wrapper<BriFlightOrder> briFlightOrderWrapper = new EntityWrapper<>();
            briFlightOrderWrapper.where("order_no={0}", order.getOrderNo());
            List<BriFlightOrder> briFlightOrders = briFlightOrderService.selectList(briFlightOrderWrapper);
            if (briFlightOrders != null && briFlightOrders.size() > 0) {
                if ("1".equals(briFlightOrders.get(0).getIsNote())) {
                    return;
                }
                briFlightOrderService.delete(briFlightOrderWrapper);
                briFlightOrderService.insert(briFlightOrderDetail);
            } else {
                briFlightOrderService.insert(briFlightOrderDetail);
            }
            List<BriFlightInfo> briFlightInfos = null;
            briFlightInfos = OrderConvert.getBriFlightInfoByJSON(detailJson, order.getOrderNo());
            Wrapper<BriFlightInfo> briFlightInfoWrapper = new EntityWrapper<>();
            briFlightInfoWrapper.where("order_no={0}", order.getOrderNo());
            flightInfoService.delete(briFlightInfoWrapper);
            if (briFlightInfos != null && briFlightInfos.size() > 0) {
                flightInfoService.insertBatch(briFlightInfos);
            }
            // end 存储航班信息

            //联系人信息
            Wrapper<BriFlightOrderContact> briFlightOrderContactWrapper = new EntityWrapper<>();
            briFlightOrderContactWrapper.where("order_no={0}", order.getOrderNo());
            orderContactService.delete(briFlightOrderContactWrapper);
            BriFlightOrderContact flightOrderContact = null;
            flightOrderContact = OrderConvert.getBriFlightOrderContactByJSON(detailJson, order.getOrderNo());
            if (flightOrderContact != null) {
                orderContactService.insert(flightOrderContact);
            }
            //end 联系人信息

            //出行人信息
            Wrapper<BriFlightPassenger> briFlightPassengerWrapper = new EntityWrapper<>();
            briFlightPassengerWrapper.where("order_no={0}", order.getOrderNo());
            passengerService.delete(briFlightPassengerWrapper);
            List<BriFlightPassenger> passengers = null;
            passengers = OrderConvert.getBriFlightPassenger(detailJson, order.getOrderNo());
            if (passengers != null && passengers.size() > 0) {
                passengerService.insertBatch(passengers);
            }
            //end  出行人信息
        }
    }

    private void dealWithApplyFlight(String tenant, BriFlightOrder flightOrderByJSON) {
        int page = 1;
        boolean flag = true;
        List<String> applyIdList = new ArrayList<>();
        if (!org.springframework.util.StringUtils.isEmpty(flightOrderByJSON.getRelateYbzId())) {
            HashMap<String, Object> paramMap = new HashMap<>();
            applyIdList.clear();
            applyIdList.add(flightOrderByJSON.getRelateYbzId());
            paramMap.put("tenant", tenant);
            paramMap.put("pagenum", 10);
            paramMap.put("pks", applyIdList);
            //暂时没传电话
            String phone = "";
            while (flag) {
                paramMap.put("page", page++);
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                logger.info("nodeBusinessTripSearching's param according applyId:tenant=" + tenant + "paramMap=" + JSON.toJSONString(paramMap));
                String res = HttpClientUtil.post(ybzBaseUrl + URL + "?phone=" + phone + "&loginType=1&tenantId=" + tenant, headers, null, JSON.toJSONString(paramMap));
                logger.info("nodeBusinessTripSearching's result according applyId:" + res);
                JSONObject resObject = JSON.parseObject(res);
                if (resObject.getBoolean("success") && "1".equals(resObject.getString("code"))) {
                    if (resObject.getJSONArray("data") != null && !resObject.getJSONArray("data").isEmpty()) {
                        JSONObject data = resObject.getJSONArray("data").getJSONObject(0);
                        if (data.getBoolean("success")) {
                            JSONArray heads = data.getJSONArray("head");
                            if (heads != null) {
                                for (Object head : heads) {
                                    JSONObject headJsonObject = (JSONObject) head;
                                    if (BriFlightOrder.ASSUME_ORG.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                                        if (headJsonObject.get("source_value") instanceof JSONObject){
                                            flightOrderByJSON.setAssumeOrg(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                                        } else if (headJsonObject.get("source_value") instanceof String) {
                                            flightOrderByJSON.setAssumeOrg(headJsonObject.getString("source_value"));
                                        }
                                    }
                                    if (BriFlightOrder.ASSUME_DEPT.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                                        if (headJsonObject.get("source_value") instanceof JSONObject){
                                            flightOrderByJSON.setAssumeDept(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                                        } else if (headJsonObject.get("source_value") instanceof String) {
                                            flightOrderByJSON.setAssumeDept(headJsonObject.getString("source_value"));
                                        }
                                    }
                                    if (BriFlightOrder.COST_PROJECT.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                                        if (headJsonObject.get("source_value") instanceof JSONObject){
                                            flightOrderByJSON.setCostProject(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                                        } else if (headJsonObject.get("source_value") instanceof String) {
                                            flightOrderByJSON.setCostProject(headJsonObject.getString("source_value"));
                                        }
                                    }
                                    if (BriFlightOrder.APPLY_USER.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                                        if (headJsonObject.get("source_value") instanceof JSONObject){
                                            flightOrderByJSON.setApplyUser(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                                        } else if (headJsonObject.get("source_value") instanceof String) {
                                            flightOrderByJSON.setApplyUser(headJsonObject.getString("source_value"));
                                        }
                                    }
                                    if (BriFlightOrder.COMPANION.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                                        if (headJsonObject.get("source_value") instanceof String) {
                                            flightOrderByJSON.setCompanion(headJsonObject.getString("source_value"));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //最后一页跳出循环
                    if (resObject.getInteger("totalPage") < page) {
                        flag = false;
                    }
                } else {
                    flag = false;
                    logger.error("根据关联申请单号匹配申请单时，返回错误");
                }
            }
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {})
    public void saveTrain(JSONObject orderJson, String tenant, String orgpk, int channelId) {
        boolean isPub = false;
        if (tenant.equals(pubTenant)) {
            isPub = true;
        }
        BriTrainOrder order = null;
        order = OrderConvert.getBriTrainOrderByJSON(orderJson);
        Wrapper<BriTrainOrder> briTrainOrderWrapper = new EntityWrapper<>();
        briTrainOrderWrapper.where("order_no={0}", order.getOrderNo());
        GetTrainOrderDetail getTrainOrderDetail = new GetTrainOrderDetail();
        getTrainOrderDetail.setOrderNo(order.getOrderNo());
        JSONObject trainDetailJson = rtpnrPublicService.getTrainOrderDetail(tenant, orgpk, getTrainOrderDetail);
        //存储火车票订单详情信息
        trainDetailJson.put("channelId", channelId);
        trainDetailJson.put("IsDomc", orderJson.getString("IsDomc"));
        CriteriaMap criteriaMap = new CriteriaMap();
        criteriaMap.put("OrderInfo.OrderNo", order.getOrderNo());
        List<JSONObject> ordersources = mongoDao.findByMap(criteriaMap, JSONObject.class, "rtpnr_train_orders");
        if (ordersources != null && ordersources.size() > 0) {
            mongoDao.deleteByMap(criteriaMap, "rtpnr_train_orders");
            mongoDao.getMongoTemplate().save(trainDetailJson, "rtpnr_train_orders");
        } else {
            mongoDao.getMongoTemplate().insert(trainDetailJson, "rtpnr_train_orders");
        }

        BriTrainOrder trainOrderDetail = null;
        trainOrderDetail = OrderConvert.getBriTrainOrderDetailByJSON(trainDetailJson);
        trainOrderDetail.setPublicOrPriveate(orderJson.getString("PublicOrPriveate"));
        trainOrderDetail.setIsDomc(orderJson.getString("IsDomc"));
        trainOrderDetail.setOrderTime(orderJson.getDate("OrderTime"));
        trainOrderDetail.setStatusType(orderJson.getString("StatusType"));
        trainOrderDetail.setYxDate(orderJson.getDate("YXDate"));
        trainOrderDetail.setSavePrice(orderJson.getBigDecimal("SavePrice"));
        trainOrderDetail.setPreiumReason(orderJson.getString("PreiumReason"));
        trainOrderDetail.setTenant(tenant);
        // 补全用户信息
        Wrapper<RtpnrUser> rtpnrUserWrapper = new EntityWrapper<>();
        rtpnrUserWrapper.eq("f_login_id", trainOrderDetail.getCreateBy());
        RtpnrUser rtpnrUser = rtpnrUserService.selectOne(rtpnrUserWrapper);
        if (null != rtpnrUser && StringUtils.isNotEmpty(rtpnrUser.getMobile())) {
            trainOrderDetail.setCreateBy(rtpnrUser.getUserName());
            // 调用dubbno服务时偶尔会有异常
            try {
                // 公户处理逻辑，若果是公户的订单，向用户中心请求数据的时候使用真实租户信息
                UcUserDto ucUserDto;
                if (isPub) {
                    trainOrderDetail.setTenant(rtpnrUser.getTenant());
                    ucUserDto = userCenterService.getCompleteUcUserDtoByPhone(rtpnrUser.getMobile(), rtpnrUser.getTenant());
                } else {
                    ucUserDto = userCenterService.getCompleteUcUserDtoByPhone(rtpnrUser.getMobile(), tenant);
                }
                if (null != ucUserDto) {
                    if (!StringUtils.isEmpty(ucUserDto.getOrgPk())) {
                        if (!ucUserDto.getOrgPk().equals(orgpk)) {
                            //对于非该组织的人员不再插入数据
                            return;
                        }
                    }
                    trainOrderDetail.setOrgPk(ucUserDto.getOrgPk());
                    trainOrderDetail.setDeptPk(ucUserDto.getDeptPk());
                    trainOrderDetail.setDepartment(ucUserDto.getDeptName());
                    trainOrderDetail.setUserId(ucUserDto.getUserId());
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.toString());
            }
        }

        //根据申请单id补全申请单信息
        dealWithApplyTrain(tenant, trainOrderDetail);

        if (trainOrderDetail != null) {
            List<BriTrainOrder> briTrainOrders = briTrainOrderService.selectList(briTrainOrderWrapper);
            if (briTrainOrders != null && briTrainOrders.size() > 0) {
                if ("1".equals(briTrainOrders.get(0).getIsNote())) {
                    return;
                }
                briTrainOrderService.delete(briTrainOrderWrapper);
                briTrainOrderService.insert(trainOrderDetail);
            } else {
                briTrainOrderService.insert(trainOrderDetail);
            }
            //end  存储火车票订单详情信息

            //出行人信息
            Wrapper<BriTrainPassenger> trainPassengerWrapper = new EntityWrapper<>();
            trainPassengerWrapper.where("order_no={0}", order.getOrderNo());
            briTrainPassengerService.delete(trainPassengerWrapper);
            List<BriTrainPassenger> passengers = null;
            passengers = OrderConvert.getBriTrainPassngerByJSON(trainDetailJson, order.getOrderNo());
            if (passengers != null && passengers.size() > 0) {
                for (int j = 0; j < passengers.size(); j++) {
                    //火车票信息
                    BriTrainPassenger briTrainPassenger = passengers.get(j);
                    String cardNo = briTrainPassenger.getCardNo();
                    Wrapper<BriTrainTicket> trainTicketWrapper = new EntityWrapper<>();
                    trainTicketWrapper.where("order_no={0}", order.getOrderNo());
                    if (!org.springframework.util.StringUtils.isEmpty(cardNo)) {
                        trainTicketWrapper.and("card_no={0}", cardNo);
                    }
                    briTrainTicketService.delete(trainTicketWrapper);
                    List<BriTrainTicket> tickets = null;
                    tickets = OrderConvert.getBriTrainTicketByJSON(trainDetailJson, cardNo);
                    if (tickets != null && tickets.size() > 0) {
                        briTrainTicketService.insertBatch(tickets);
                    }
                    //end 火车票信息
                }
                briTrainPassengerService.insertBatch(passengers);
            }
            //end  出行人信息

            //支付信息(中航易购目前获取不到支付信息表内相关内容)
//            Wrapper<BriTrainPayment> trainPaymentWrapper = new EntityWrapper<>();
//            trainPaymentWrapper.where("order_no={0}", order.getOrderNo());
//            briTrainPaymentService.delete(trainPaymentWrapper);
//            BriTrainPayment payment = OrderConvert.getBriTrainPaymentByJSON(trainDetailJson, order.getOrderNo());
//            if (payment != null) {
//                 briTrainPaymentService.insert(payment);
//            }
            //end  支付信息

            //审批流程信息
            Wrapper<BriTrainApprovalFlow> trainApprovalFlowEntityWrapper = new EntityWrapper<>();
            trainApprovalFlowEntityWrapper.where("order_no={0}", order.getOrderNo());
            briTrainApprovalFlowService.delete(trainApprovalFlowEntityWrapper);
            List<BriTrainApprovalFlow> approvalFlows = null;
            approvalFlows = OrderConvert.getBriTrainApprovalFlowByJSON(trainDetailJson, order.getOrderNo());
            if (approvalFlows != null && approvalFlows.size() > 0) {
                briTrainApprovalFlowService.insertBatch(approvalFlows);
            }
            //end  审批流程信息
        }
    }

    private void dealWithApplyTrain(String tenant, BriTrainOrder trainOrderByJSON) {
        int page = 1;
        boolean flag = true;
        List<String> applyIdList = new ArrayList<>();
        if (!org.springframework.util.StringUtils.isEmpty(trainOrderByJSON.getRelateYBZID())) {
            HashMap<String, Object> paramMap = new HashMap<>();
            applyIdList.clear();
            applyIdList.add(trainOrderByJSON.getRelateYBZID());
            paramMap.put("tenant", tenant);
            paramMap.put("pagenum", 10);
            paramMap.put("pks", applyIdList);
            //暂时没传电话
            String phone = "";
            while (flag) {
                paramMap.put("page", page++);
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                logger.info("nodeBusinessTripSearching's param according applyId:tenant=" + tenant + "paramMap=" + JSON.toJSONString(paramMap));
                String res = HttpClientUtil.post(ybzBaseUrl + URL + "?phone=" + phone + "&loginType=1&tenantId=" + tenant, headers, null, JSON.toJSONString(paramMap));
                logger.info("nodeBusinessTripSearching's result according applyId:" + res);
                JSONObject resObject = JSON.parseObject(res);
                if (resObject.getBoolean("success") && "1".equals(resObject.getString("code"))) {
                    if (resObject.getJSONArray("data") != null && !resObject.getJSONArray("data").isEmpty()) {
                        JSONObject data = resObject.getJSONArray("data").getJSONObject(0);
                        if (data.getBoolean("success")) {
                            JSONArray heads = data.getJSONArray("head");
                            if (heads != null) {
                                for (Object head : heads) {
                                    JSONObject headJsonObject = (JSONObject) head;
                                    if (BriTrainOrder.ASSUME_ORG.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                                        if (headJsonObject.get("source_value") instanceof JSONObject) {
                                            trainOrderByJSON.setAssumeOrg(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                                        } else if (headJsonObject.get("source_value") instanceof String) {
                                            trainOrderByJSON.setAssumeOrg(headJsonObject.getString("source_value"));
                                        }
                                    }
                                    if (BriTrainOrder.ASSUME_DEPT.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                                        if (headJsonObject.get("source_value") instanceof JSONObject) {
                                            trainOrderByJSON.setAssumeDept(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                                        } else if (headJsonObject.get("source_value") instanceof String) {
                                            trainOrderByJSON.setAssumeDept(headJsonObject.getString("source_value"));
                                        }
                                    }
                                    if (BriTrainOrder.COST_PROJECT.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                                        if (headJsonObject.get("source_value") instanceof JSONObject) {
                                            trainOrderByJSON.setCostProject(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                                        } else if (headJsonObject.get("source_value") instanceof String) {
                                            trainOrderByJSON.setCostProject(headJsonObject.getString("source_value"));
                                        }
                                    }
                                    if (BriTrainOrder.APPLY_USER.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                                        if (headJsonObject.get("source_value") instanceof JSONObject) {
                                            trainOrderByJSON.setApplyUser(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                                        } else if (headJsonObject.get("source_value") instanceof String) {
                                            trainOrderByJSON.setApplyUser(headJsonObject.getString("source_value"));
                                        }
                                    }
                                    if (BriTrainOrder.COMPANION.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                                        if (headJsonObject.get("source_value") instanceof String) {
                                            trainOrderByJSON.setCompanion(headJsonObject.getString("source_value"));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //最后一页跳出循环
                    if (resObject.getInteger("totalPage") < page) {
                        flag = false;
                    }
                } else {
                    flag = false;
                    logger.error("根据关联申请单号匹配申请单时，返回错误");
                }
            }
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {})
    public void saveHotel(JSONObject orderJson, String tenant, String orgpk, int channelId) {
        boolean isPub = false;
        if (tenant.equals(pubTenant)) {
            isPub = true;
        }
        BriHotelOrder order = null;
        order = OrderConvert.getBriHotelOrderByJSON(orderJson);
        GetHotelOrderDetail detail = new GetHotelOrderDetail();
        detail.setOrderNo(order.getOrderNo());
        JSONObject hotelDetailJson = rtpnrPublicService.getHotelOrderDetail(tenant, orgpk, detail);
        hotelDetailJson.put("channelId", channelId);
        hotelDetailJson.put("IsDomc", orderJson.getString("IsDomc"));
        // mongodb save
        CriteriaMap criteriaMap = new CriteriaMap();
        criteriaMap.put("OrderInfo.OrderNo", order.getOrderNo());
        List<JSONObject> ordersources = mongoDao.findByMap(criteriaMap, JSONObject.class, "rtpnr_hotel_orders");
        if (ordersources != null && ordersources.size() > 0) {
            mongoDao.deleteByMap(criteriaMap, "rtpnr_hotel_orders");
            mongoDao.getMongoTemplate().save(hotelDetailJson, "rtpnr_hotel_orders");
        } else {
            mongoDao.getMongoTemplate().insert(hotelDetailJson, "rtpnr_hotel_orders");
        }
        //end mongodb save

        //返回酒店订单对象，包含订单详情
        BriHotelOrder briHotelOrderDetail = null;
        briHotelOrderDetail = OrderConvert.getBriHotelOrderDetailByJSON(hotelDetailJson);
        briHotelOrderDetail.setOrderNo(order.getOrderNo());
        briHotelOrderDetail.setCreateBy(order.getCreateBy());
        briHotelOrderDetail.setPublicOrPrivate(order.getPublicOrPrivate());
        briHotelOrderDetail.setIsDomc(order.getIsDomc());
        briHotelOrderDetail.setOrderStatus(order.getOrderStatus());
        briHotelOrderDetail.setOrderTime(order.getOrderTime());
        briHotelOrderDetail.setPaymentPrice(order.getPaymentPrice());
        briHotelOrderDetail.setStatusType(order.getStatusType());
        briHotelOrderDetail.setYxDate(order.getYxDate());
        briHotelOrderDetail.setSavePrice(order.getSavePrice());
        briHotelOrderDetail.setPreiumReason(order.getPreiumReason());
        briHotelOrderDetail.setTenant(tenant);
        // 补全用户信息
        Wrapper<RtpnrUser> rtpnrUserWrapper = new EntityWrapper<>();
        rtpnrUserWrapper.eq("f_login_id", briHotelOrderDetail.getCreateBy());
        RtpnrUser rtpnrUser = rtpnrUserService.selectOne(rtpnrUserWrapper);
        if (null != rtpnrUser && StringUtils.isNotEmpty(rtpnrUser.getMobile())) {
            briHotelOrderDetail.setCreateBy(rtpnrUser.getUserName());
            // 调用dubbno服务时偶尔会有异常
            try {
                UcUserDto ucUserDto;
                if (isPub) {
                    briHotelOrderDetail.setTenant(rtpnrUser.getTenant());
                    ucUserDto = userCenterService.getCompleteUcUserDtoByPhone(rtpnrUser.getMobile(), rtpnrUser.getTenant());
                } else {
                    ucUserDto = userCenterService.getCompleteUcUserDtoByPhone(rtpnrUser.getMobile(), tenant);
                }
                if (null != ucUserDto) {
                    if (!org.springframework.util.StringUtils.isEmpty(ucUserDto.getOrgPk())) {
                        if (!ucUserDto.getOrgPk().equals(orgpk)) {
                            return;//对于非该组织的人员不再插入数据
                        }
                    }
                    briHotelOrderDetail.setUserId(ucUserDto.getUserId());
                    briHotelOrderDetail.setOrgPk(ucUserDto.getOrgPk());
                    briHotelOrderDetail.setDepartment(ucUserDto.getDeptName());
                    briHotelOrderDetail.setDeptPk(ucUserDto.getDeptPk());
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(e.toString());
            }
        }

        //根据申请单id补全申请单信息
        dealWithApplyHotel(tenant, briHotelOrderDetail);

        if (briHotelOrderDetail != null) {
            Wrapper<BriHotelOrder> briHotelOrderWrapper = new EntityWrapper<>();
            briHotelOrderWrapper.where("order_no={0}", order.getOrderNo());
            List<BriHotelOrder> briHoteltOrders = briHotelOrderService.selectList(briHotelOrderWrapper);
            if (briHoteltOrders != null && briHoteltOrders.size() > 0) {
                if ("1".equals(briHoteltOrders.get(0).getIsNote())) {
                    return;
                }
                briHotelOrderService.delete(briHotelOrderWrapper);
                briHotelOrderService.insert(briHotelOrderDetail);
            } else {
                briHotelOrderService.insert(briHotelOrderDetail);
            }
            //酒店房间及入住人信息
            Wrapper<BriHotelRoom> briHotelRoomWrapperWrapper = new EntityWrapper<>();
            briHotelRoomWrapperWrapper.where("order_no={0}", order.getOrderNo());
            hotelRoomService.delete(briHotelRoomWrapperWrapper);
            List<BriHotelRoom> briHotelRooms = null;
            briHotelRooms = OrderConvert.getBriHotelRoomByJSON(hotelDetailJson, order.getOrderNo());
            if (briHotelRooms != null && briHotelRooms.size() > 0) {
                hotelRoomService.insertBatch(briHotelRooms);
            }
            // end 存储酒店房间及入住人信息

            //审批流程信息
            Wrapper<BriHotelApprovalFlow> briHotelApprovalFlowWrapper = new EntityWrapper<>();
            briHotelApprovalFlowWrapper.where("order_no={0}", order.getOrderNo());
            hotelApprovalFlowService.delete(briHotelApprovalFlowWrapper);
            List<BriHotelApprovalFlow> briHotelApprovalFlows = null;
            briHotelApprovalFlows = OrderConvert.getBriHotelApprovalFlowByJSON(hotelDetailJson, order.getOrderNo());
            if (briHotelApprovalFlows != null && briHotelApprovalFlows.size() > 0) {
                hotelApprovalFlowService.insertBatch(briHotelApprovalFlows);
            }
            //end  审批流程信息
        }
    }

    private void dealWithApplyHotel(String tenant, BriHotelOrder hotelOrderByJSON) {
        int page = 1;
        boolean flag = true;
        List<String> applyIdList = new ArrayList<>();
        if (!org.springframework.util.StringUtils.isEmpty(hotelOrderByJSON.getRelateYBZID())) {
            HashMap<String, Object> paramMap = new HashMap<>();
            applyIdList.clear();
            applyIdList.add(hotelOrderByJSON.getRelateYBZID());
            paramMap.put("tenant", tenant);
            paramMap.put("pagenum", 10);
            paramMap.put("pks", applyIdList);
            //暂时没传电话
            String phone = "";
            while (flag) {
                paramMap.put("page", page++);
                HashMap<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                logger.info("nodeBusinessTripSearching's param according applyId:tenant=" + tenant + "paramMap=" + JSON.toJSONString(paramMap));
                String res = HttpClientUtil.post(ybzBaseUrl + URL + "?phone=" + phone + "&loginType=1&tenantId=" + tenant, headers, null, JSON.toJSONString(paramMap));
                logger.info("nodeBusinessTripSearching's result according applyId:" + res);
                JSONObject resObject = JSON.parseObject(res);
                if (resObject.getBoolean("success") && "1".equals(resObject.getString("code"))) {
                    if (resObject.getJSONArray("data") != null && !resObject.getJSONArray("data").isEmpty()) {
                        JSONObject data = resObject.getJSONArray("data").getJSONObject(0);
                        if (data.getBoolean("success")) {
                            JSONArray heads = data.getJSONArray("head");
                            if (heads != null) {
                                for (Object head : heads) {
                                    JSONObject headJsonObject = (JSONObject) head;
                                    if (BriHotelOrder.ASSUME_ORG.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                                        if (headJsonObject.get("source_value") instanceof JSONObject) {
                                            hotelOrderByJSON.setAssumeOrg(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                                        } else if (headJsonObject.get("source_value") instanceof String) {
                                            hotelOrderByJSON.setAssumeOrg(headJsonObject.getString("source_value"));
                                        }
                                    }
                                    if (BriHotelOrder.ASSUME_DEPT.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                                        if (headJsonObject.get("source_value") instanceof JSONObject) {
                                            hotelOrderByJSON.setAssumeDept(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                                        } else if (headJsonObject.get("source_value") instanceof String) {
                                            hotelOrderByJSON.setAssumeDept(headJsonObject.getString("source_value"));
                                        }
                                    }
                                    if (BriHotelOrder.COST_PROJECT.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                                        if (headJsonObject.get("source_value") instanceof JSONObject) {
                                            hotelOrderByJSON.setCostProject(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                                        } else if (headJsonObject.get("source_value") instanceof String) {
                                            hotelOrderByJSON.setCostProject(headJsonObject.getString("source_value"));
                                        }
                                    }
                                    if (BriHotelOrder.APPLY_USER.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                                        if (headJsonObject.get("source_value") instanceof JSONObject) {
                                            hotelOrderByJSON.setApplyUser(headJsonObject.getJSONObject("source_value").getString("id") + "," + headJsonObject.getJSONObject("source_value").getString("name"));
                                        } else if (headJsonObject.get("source_value") instanceof String) {
                                            hotelOrderByJSON.setApplyUser(headJsonObject.getString("source_value"));
                                        }
                                    }
                                    if (BriHotelOrder.COMPANION.equals(headJsonObject.getString("source_code")) && headJsonObject.get("source_value") != null) {
                                        if (headJsonObject.get("source_value") instanceof String) {
                                            hotelOrderByJSON.setCompanion(headJsonObject.getString("source_value"));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //最后一页跳出循环
                    if (resObject.getInteger("totalPage") < page) {
                        flag = false;
                    }
                } else {
                    flag = false;
                    logger.error("根据关联申请单号匹配申请单时，返回错误");
                }
            }
        }
    }
}
